<template>
  <div>
    <el-dialog
      v-model="_dialogVisible"
      :title="`${menu_id ? '修改' : '添加'}菜单`"
      :before-close="handleClose"
      destroy-on-close
      draggable
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80">
        <el-form-item label="菜单类型" prop="menu_type">
          <el-radio-group v-model="formData.menu_type">
            <el-radio-button :label="1">目录</el-radio-button>
            <el-radio-button :label="2">菜单</el-radio-button>
            <el-radio-button :label="3">按钮</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parent_id">
          <el-tree-select
            v-model="formData.parent_id"
            :data="treeData"
            :props="{ label: 'menu_name', value: 'menu_id' }"
            check-strictly
            placeholder="请选择上级菜单"
          />
        </el-form-item>
        <el-form-item v-if="formData.menu_type != 3" label="图标" prop="icon">
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input v-model="formData.icon" placeholder="请输入图标" />
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="iconDialogVisible = true">
                选择图标
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menu_name">
          <el-input v-model="formData.menu_name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item v-if="formData.menu_type == 2" label="菜单url" prop="url">
          <el-input v-model="formData.url" placeholder="请输入菜单url" />
        </el-form-item>
        <el-form-item
          v-if="formData.menu_type == 3"
          label="权限标识"
          prop="value"
        >
          <el-input v-model="formData.value" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            placeholder="请输入排序"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="菜单状态" prop="menu_status">
          <el-radio-group v-model="formData.menu_status">
            <el-radio-button :label="2">启用</el-radio-button>
            <el-radio-button :label="1">停用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleSubmit">
          {{ menu_id ? '修改' : '添加' }}
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
  <Icon
    v-model:dialogVisible="iconDialogVisible"
    @success="handleIconSuccess"
  />
</template>

<script setup lang="ts">
import { FormInstance, FormRules } from 'element-plus'
import { ref, watch, computed } from 'vue'
import { getRuleVoList, show, store, update } from '@/api/auth/rule'
import { VoListItem, ruleParams } from '@/api/auth/model/ruleModel'
import handleTree from '@/utils/tree'
import { useForm } from '@/hooks'
import Icon from '../../Icon.vue'

const { resetForm, validate } = useForm()

const iconDialogVisible = ref<boolean>(false)

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  menu_id: {
    type: Number,
    default: 0,
  },
})
const emit = defineEmits(['update:dialogVisible', 'success'])

const _dialogVisible = ref<boolean>(false)

const formRef = ref<FormInstance>(null!)

let formData = ref<ruleParams | any>({
  menu_id: 0,
  menu_type: 1,
  parent_id: 0,
  icon: '',
  menu_name: '',
  sort: 0,
  url: '',
  value: '',
  menu_status: 2,
})

const treeData = ref<VoListItem[]>([])

watch(
  () => props.dialogVisible,
  () => {
    props.dialogVisible && getRuleParentList()
    _dialogVisible.value = props.dialogVisible
  }
)

watch(
  () => _dialogVisible.value,
  () => {
    emit('update:dialogVisible', _dialogVisible.value)
  }
)

watch(
  () => [props.menu_id, props.dialogVisible],
  () => {
    props.dialogVisible && props.menu_id && detail()
  }
)

const getRuleParentList = async () => {
  const { code, data, message } = await getRuleVoList()
  if (code != 200) {
    ElMessage.error(message)
    return
  }
  treeData.value = handleTree.handleTree(
    data,
    'menu_id',
    'parent_id',
    'children'
  ) as never[]
  treeData.value?.unshift({ menu_id: 0, parent_id: 0, menu_name: '无' })
}

const detail = async () => {
  if (props.menu_id) {
    const { code, message, data } = await show({ menu_id: props.menu_id })
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    formData.value = data
  }
}

const handleClose = () => {
  resetForm(formRef.value)
  _dialogVisible.value = false
}

const rules = computed<FormRules<ruleParams>>(() => ({
  menu_type: {
    required: true,
    message: '请选择菜单类型',
    trigger: 'blur',
  },
  parent_id: {
    required: true,
    message: '请选择上级菜单',
    trigger: 'blur',
  },
  icon: {
    required: formData.value.menu_type != 3,
    message: '请输入图标',
    trigger: 'blur',
  },
  menu_name: {
    required: true,
    message: '请输入菜单名称',
    trigger: 'blur',
  },
  url: {
    required: formData.value.menu_type == 2,
    message: '请输入菜单url',
    trigger: 'blur',
  },
  value: {
    required: formData.value.menu_type == 3,
    message: '请输入权限标识',
    trigger: 'blur',
  },
  menu_status: {
    required: true,
    message: '请选择菜单状态',
    trigger: 'blur',
  },
}))

const handleSubmit = async () => {
  await validate(formRef.value)
  //发送请求
  let result
  if (!props.menu_id) {
    result = await store(formData.value)
  } else {
    result = await update(formData.value)
  }
  const { code, message } = result
  if (code != 200) {
    ElMessage.error(`${props.menu_id ? '修改' : '添加'}${message}`)
    return
  }
  handleClose()
  ElMessage.success(`${props.menu_id ? '修改' : '添加'}${message}`)
  emit('success')
}

const handleIconSuccess = (icon: string) => {
  formData.value.icon = icon
  iconDialogVisible.value = false
}
</script>

<style scoped></style>
